<template>
    <div ref="chartRef" class="echartsClass"></div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import * as echarts from "echarts";
import { useCompanyDataStore } from '@/store/companys'

const companyDataStore = useCompanyDataStore()

interface EmployeeStats {
    name: string;
    value: number;
    color: string;
}

const props = defineProps<{
    data: EmployeeStats[]
}>()

const chartRef = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

const initChart = () => {
    if (!chartRef.value) return;
    chartInstance?.dispose();
    chartInstance = echarts.init(chartRef.value);
    updateChart();
    window.addEventListener('resize', handleChartResize);
}

const updateChart = () => {
    if (!chartInstance) return;
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: props.data.map(item => item.name)
        },
        series: [
            {
                name: '员工统计',
                type: 'pie',
                center: ['35%', '50%'],
                radius: ['60%', '90%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 0,
                    borderColor: '#fff',
                    borderWidth: 0
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: false,
                        fontSize: '18',
                        fontWeight: 'bold',
                        formatter: '{b}\n{c}人 ({d}%)'
                    }
                },
                labelLine: {
                    show: false
                },
                data: props.data.map(item => ({
                    value: item.value,
                    name: item.name,
                    itemStyle: { color: item.color }
                }))
            }
        ]
    };

    chartInstance.setOption(option);
}

const handleChartResize = () => {
    chartInstance?.resize();
}

const cleanupChart = () => {
    window.removeEventListener('resize', handleChartResize);
    chartInstance?.dispose();
};

onBeforeUnmount(() => {
    cleanupChart();
});

onMounted(() => {
    initChart()
})

watch(
    () => companyDataStore.currentComanyInfo,
    (newCompany) => {
        if (newCompany) {
            setTimeout(() => {
                initChart()
            }, 500)
        }
    },
    { deep: true }
)
</script>
<style scoped>
.echartsClass {
    width: 100%;
    height: 200px;
}
</style>